<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" type="text/css" href="test.css">
</head>
<body>
    <div class="mainbody">
        <form>
            <div class="formbody">
                <label for="username"><input class="input" type="text" name="username" id="username">用户名:</label>
                <p></p>
                <label for="pwd"><input class="input" type="text" name="psw" id="psw">密码:</label>
            </div>
            <button type="button" class="buttonbody button" id="btn" value="登     录">登    录</button>
            <div class="select">
                <input type="checkbox" id="check">七天免登录
            </div>
        </form>
    </div>
</body>
</html>
<script>
    function setCookie(cookName, cookieVal, expires) {
        let d = new Date();
        d.setDate(d.getDate() + expires)
        document.cookie = cookName + "=" + cookieVal + ";path=/;expires=" + d.toUTCString();
    }
    let oName = document.getElementById("username");
    let oPsw = document.getElementById("psw");
    let oCheck = document.getElementById("check");
    let oBtn = document.getElementById("btn");
    getCookie("user");
    function getCookie(cookName) {
        let cookie = document.cookie;
        let arr = cookie.split("; ");
        for (let i = 0; i < arr.length; i++){
            let newArr = arr[i].split("=");
            if(newArr[0] == cookName){
                let obj = JSON.parse(newArr[1]);
                console.log(obj);
                if(obj.checked) {
                    oName.value = obj.username;
                    oPsw.value = obj.password;
                    if(obj.username=="admin"&&obj.password=="123"){
                        window.location.href="test-body.html";
                    }
                }
                else{
                    setCookie("user",0,0)
                }
            }
        }
    }

    oBtn.onclick = function () {
        let username=document.getElementById("username").value;
        let password=document.getElementById("psw").value;
        let checked=oCheck.checked;
        if(username=="admin"&&password=="123"){
            console.log("选中");
            let obj = {};
            obj.username = oName.value;
            obj.password = oPsw.value;
            obj.checked = checked;
            console.log(obj);
            let str = JSON.stringify(obj)
            setCookie("user", str, 7);
            window.location.href="test-body.html";
        }
        else {
            alert("账号密码错误");
        }
    }

</script>
